package cn.ll.po;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Hibernate;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

/**
 * A data access object (DAO) providing persistence and search support for
 * Customer entities. Transaction control of the save(), update() and delete()
 * operations can directly support Spring container-managed transactions or they
 * can be augmented to handle user-managed Spring transactions. Each of these
 * methods provides additional information for how to configure it for the
 * desired type of transaction control.
 * 
 * @see cn.ll.po.Customer
 * @author MyEclipse Persistence Tools
 */

public class CustomerDAO extends HibernateDaoSupport {
	private static final Log log = LogFactory.getLog(CustomerDAO.class);
	// property constants
	public static final String CUSTOMERNAME = "customername";
	public static final String COMTYPE = "comtype";
	public static final String SUBDEPARTMENT = "subdepartment";
	public static final String STATUS = "status";
	public static final String CONTINENT = "continent";
	public static final String COUNTRY = "country";
	public static final String CITY = "city";
	public static final String TEL = "tel";
	public static final String FAX = "fax";
	public static final String WEBSITE = "website";
	public static final String ADDRESS = "address";
	public static final String USERID = "userid";
	public static final String CONTACTORNAME = "contactorname";
	public static final String CONTACTGENDER = "contactgender";
	public static final String CONTACTOREMAIL = "contactoremail";
	public static final String CONTACTORPOSITION = "contactorposition";
	public static final String CONTACTTEL = "contacttel";
	public static final String CONTACTMOBILE = "contactmobile";
	public static final String COMSTYLE = "comstyle";
	public static final String REMARKS = "remarks";

	protected void initDao() {
		// do nothing
	}

	public void save(Customer transientInstance) {
		log.debug("saving Customer instance");
		try {
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re) {
			log.error("save failed", re);
			throw re;
		}
	}

	public void update(Customer transientInstance) {
		log.debug("update Customer instance");
		try {
			getHibernateTemplate().update(transientInstance);
			log.debug("update successful");
		} catch (RuntimeException re) {
			log.error("update failed", re);
			throw re;
		}
	}

	public void delete(Customer persistentInstance) {
		log.debug("deleting Customer instance");
		try {
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re) {
			log.error("delete failed", re);
			throw re;
		}
	}

	public Customer findById(java.lang.String id) {
		log.debug("getting Customer instance with id: " + id);
		try {
			Customer instance = (Customer) getHibernateTemplate().get("cn.ll.po.Customer", id);
			return instance;
		} catch (RuntimeException re) {
			log.error("get failed", re);
			throw re;
		}
	}

	public List<Customer> findByExample(Customer instance) {
		log.debug("finding Customer instance by example");
		try {
			List<Customer> results = (List<Customer>) getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: " + results.size());
			return results;
		} catch (RuntimeException re) {
			log.error("find by example failed", re);
			throw re;
		}
	}

	public List findByProperty(String propertyName, Object value) {
		log.debug("finding Customer instance with property: " + propertyName + ", value: " + value);
		try {
			String queryString = "from Customer as model where model." + propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re) {
			log.error("find by property name failed", re);
			throw re;
		}
	}

	public List<Customer> findByCustomername(Object customername) {
		return findByProperty(CUSTOMERNAME, customername);
	}

	public List<Customer> findByComtype(Object comtype) {
		return findByProperty(COMTYPE, comtype);
	}

	public List<Customer> findBySubdepartment(Object subdepartment) {
		return findByProperty(SUBDEPARTMENT, subdepartment);
	}

	public List<Customer> findByStatus(Object status) {
		return findByProperty(STATUS, status);
	}

	public List<Customer> findByContinent(Object continent) {
		return findByProperty(CONTINENT, continent);
	}

	public List<Customer> findByCountry(Object country) {
		return findByProperty(COUNTRY, country);
	}

	public List<Customer> findByCity(Object city) {
		return findByProperty(CITY, city);
	}

	public List<Customer> findByTel(Object tel) {
		return findByProperty(TEL, tel);
	}

	public List<Customer> findByFax(Object fax) {
		return findByProperty(FAX, fax);
	}

	public List<Customer> findByWebsite(Object website) {
		return findByProperty(WEBSITE, website);
	}

	public List<Customer> findByAddress(Object address) {
		return findByProperty(ADDRESS, address);
	}

	public List<Customer> findByUserid(Object userid) {
		return findByProperty(USERID, userid);
	}

	public List<Customer> findByContactorname(Object contactorname) {
		return findByProperty(CONTACTORNAME, contactorname);
	}

	public List<Customer> findByContactgender(Object contactgender) {
		return findByProperty(CONTACTGENDER, contactgender);
	}

	public List<Customer> findByContactoremail(Object contactoremail) {
		return findByProperty(CONTACTOREMAIL, contactoremail);
	}

	public List<Customer> findByContactorposition(Object contactorposition) {
		return findByProperty(CONTACTORPOSITION, contactorposition);
	}

	public List<Customer> findByContacttel(Object contacttel) {
		return findByProperty(CONTACTTEL, contacttel);
	}

	public List<Customer> findByContactmobile(Object contactmobile) {
		return findByProperty(CONTACTMOBILE, contactmobile);
	}

	public List<Customer> findByComstyle(Object comstyle) {
		return findByProperty(COMSTYLE, comstyle);
	}

	public List<Customer> findByRemarks(Object remarks) {
		return findByProperty(REMARKS, remarks);
	}

	public List findAll() {
		log.debug("finding all Customer instances");
		try {
			String queryString = "from Customer";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public Map findCustomerNotDel(Map condition) {
		log.debug("finding Customer instances by hql");
		try {
			Integer start = null;
			Integer limit = null;
			if (condition.get("startline") != null) {
				start = (Integer) condition.get("startline");
			}
			if (condition.get("num") != null) {
				limit = (Integer) condition.get("num");
			}
			String queryString = "from Customer as model where model.status <> ? ";
			Session session = this.getHibernateTemplate().getSessionFactory().openSession();
			Query query = session.createQuery(queryString);
			query.setInteger(0, 3);

			Map map = new HashMap(0);
			List list = query.list();
			int size = list.size();
			if (start != null && limit != null) {
				int toIndex = start + limit > size ? size : start + limit;
				map.put("list", list.subList(start, toIndex));
			} else {
				map.put("list", list);
			}
			map.put("totalcount", size);
			session.close();
			return map;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public Map findSalesCus(String salesid, int start, int limit) {
		log.debug("finding Customer instances by hql");
		try {
			String queryString = "from Customer as model where model.status <> ? and model.userid = ?";
			// Object[] obj ={3,salesid};
			Session session = this.getHibernateTemplate().getSessionFactory().openSession();
			Query query = session.createQuery(queryString);
			query.setInteger(0, 3);
			query.setString(1, salesid);
			// query.setFirstResult(startline);
			// query.setMaxResults(num);
			List list = query.list();
			int size = list.size();
			Map map = new HashMap(0);
			int toIndex = start + limit > size ? size : start + limit;
			map.put("list", list.subList(start, toIndex));
			map.put("totalcount", size);
			session.close();
			return map;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public Customer merge(Customer detachedInstance) {
		log.debug("merging Customer instance");
		try {
			Customer result = (Customer) getHibernateTemplate().merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re) {
			log.error("merge failed", re);
			throw re;
		}
	}

	public void attachDirty(Customer instance) {
		log.debug("attaching dirty Customer instance");
		try {
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public void attachClean(Customer instance) {
		log.debug("attaching clean Customer instance");
		try {
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re) {
			log.error("attach failed", re);
			throw re;
		}
	}

	public List selectNameList() {
		Session session = this.getSessionFactory().openSession();
		String sql = "select id,customername from customer";
		Query query = session.createSQLQuery(sql).addScalar("id", Hibernate.STRING).addScalar("customername",
				Hibernate.STRING);
		List list = query.list();
		int size = list.size();
		List list_send = new ArrayList();
		for (int i = 0; i < size; i++) {
			Object[] item = (Object[]) list.get(i);
			Map map = new java.util.HashMap(0);
			map.put("key", String.valueOf(item[0]));
			map.put("value", String.valueOf(item[1]));
			list_send.add(map);

		}
		return list_send;

	}

	public List<Customer> fuzzyQuery(String customername, String subdepartment, String tel, String address) {
		Session session = this.getSessionFactory().openSession();
		List<Customer> list = new ArrayList<Customer>();
		String sql_1 = "";
		String sql_2 = "";
		String sql_3 = "";
		String sql_4 = "";
		String sql = "";
		if (customername != null && customername.length() > 0) {
			sql_1 = " select * from customer where customername like '%" + customername + "%' ";
			sql = sql_1;
		}
		if (subdepartment != null && subdepartment.length() > 0) {

			sql_2 = " select * from customer where subdepartment like '%" + subdepartment + "%' ";
			if (sql_1.length() > 0) {
				sql += " union " + sql_2;
			} else {
				sql = sql_2;
			}
		}
		if (tel != null && tel.length() > 0) {
			sql_3 = " select * from customer where tel like '%" + tel + "%' ";
			if (sql_1.length() > 0 || sql_2.length() > 0) {
				sql += " union " + sql_3;
			} else {
				sql = sql_3;
			}
		}
		if (address != null && address.length() > 0) {
			sql_4 = " select * from customer where address like '%" + address + "%' ";
			if (sql_1.length() > 0 || sql_2.length() > 0 || sql_3.length() > 0) {
				sql += " union " + sql_4;
			} else {
				sql = sql_4;
			}

		}
		System.out.println(sql);

		if (!sql.equals("")) {

			Query query = session.createSQLQuery(sql).addEntity(Customer.class);
			list = query.list();
			if (list != null) {
				int size = list.size();
				String like = "近似";
				String equal = "相等";
				String unequal = "完全不同";
				for (int i = 0; i < size; i++) {
					Customer customer = list.get(i);
					// 判断客户名称
					if (customer.getCustomername() != null && customername != null
							&& customer.getCustomername().equalsIgnoreCase(customername)) {
						customer.setCustomername(equal);
					} else if (customer.getCustomername() != null
							&& (customer.getCustomername()).contains(customername)) {
						customer.setCustomername(like);
					} else {
						customer.setCustomername(unequal);
					}

					// 判断二级部门
					if (customer.getSubdepartment() != null && subdepartment != null
							&& customer.getSubdepartment().equalsIgnoreCase(subdepartment)) {
						customer.setSubdepartment(equal);
					} else if (customer.getSubdepartment() != null && subdepartment != null
							&& (customer.getSubdepartment()).contains(subdepartment)) {
						customer.setSubdepartment(like);
					} else {
						customer.setSubdepartment(unequal);
					}

					// 判断地址
					if (customer.getAddress() != null && address != null
							&& customer.getAddress().equalsIgnoreCase(address)) {
						customer.setAddress(equal);
					} else if (customer.getAddress() != null && address != null
							&& (customer.getAddress()).contains(address)) {
						customer.setAddress(like);
					} else {
						customer.setAddress(unequal);
					}

					// 判断电话
					if (customer.getTel() != null && tel != null && customer.getTel().equalsIgnoreCase(tel)) {
						customer.setTel(equal);
					} else if (customer.getTel() != null && tel != null && (customer.getTel()).contains(tel)) {
						customer.setTel(like);
					} else {
						customer.setTel(unequal);
					}
				}
			}
		}
		return list;
	}

	public static CustomerDAO getFromApplicationContext(ApplicationContext ctx) {
		return (CustomerDAO) ctx.getBean("CustomerDAO");
	}

	public Map findByStatus(int status, Integer start, Integer limit) {

		log.debug("finding Customer instances by hql");
		try {
			String queryString = "from Customer as model where model.status = ? ";
			// Object[] obj ={3,salesid};
			Session session = this.getHibernateTemplate().getSessionFactory().openSession();
			Query query = session.createQuery(queryString);
			query.setInteger(0, status);

			// query.setFirstResult(startline);
			// query.setMaxResults(num);
			List list = query.list();

			int size = list.size();
			Map map = new HashMap(0);
			map.put("totalcount", size);
			int toIndex = start + limit > size ? size : start + limit;
			map.put("list", list.subList(start, toIndex));
			session.close();
			return map;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}
	}

	public Long count() {

		log.debug("finding Customer instances by hql");
		try {
			String queryString = "select count(*) from Customer as model ";
			List list = this.getHibernateTemplate().find(queryString);

			Long count = (Long) list.get(0);

			return count;
		} catch (RuntimeException re) {
			log.error("find all failed", re);
			throw re;
		}

	}
}